package org.news.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.news.web.constant.ApplyCreatorsConstant;
import org.news.web.constant.CreatorsConstant;
import org.news.web.constant.UsersConstant;
import org.news.web.domain.Creators;
import org.news.web.domain.Users;
import org.news.web.mapper.CreatorsMapper;
import org.news.web.mapper.UsersMapper;
import org.news.web.service.INotificationsService;
import org.springframework.stereotype.Service;
import org.news.web.domain.bo.ApplyCreatorsBo;
import org.news.web.domain.vo.ApplyCreatorsVo;
import org.news.web.domain.ApplyCreators;
import org.news.web.mapper.ApplyCreatorsMapper;
import org.news.web.service.IApplyCreatorsService;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 作者申请审核功能Service业务层处理
 *
 * @author Gu Ci
 * @date 2024-03-31
 */
@RequiredArgsConstructor
@Service
public class ApplyCreatorsServiceImpl implements IApplyCreatorsService {

    private final ApplyCreatorsMapper baseMapper;

    private final CreatorsMapper creatorsMapper;


    private final UsersMapper usersMapper;

    private final UsersServiceImpl usersService;

    private final INotificationsService notificationsService;

    /**
     * 查询作者申请审核功能
     */
    @Override
    public ApplyCreatorsVo queryById(Long userCreatorsId){
        return baseMapper.selectVoById(userCreatorsId);
    }

    /**
     * 查询作者申请审核功能列表
     */
    @Override
    public TableDataInfo<ApplyCreatorsVo> queryPageList(ApplyCreatorsBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ApplyCreators> lqw = buildQueryWrapper(bo);
        Page<ApplyCreatorsVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        /**
         * 添加用户名信息
         */
        List<ApplyCreatorsVo> list = result.getRecords();
        Set<Long> collect = list.stream().map(ApplyCreatorsVo::getUserId).collect(Collectors.toSet());
        if(ObjectUtils.isEmpty(collect)){
            return TableDataInfo.build(result);
        }
        List<Users> users = usersMapper.selectList(new LambdaQueryWrapper<Users>().in(Users::getUserId, collect));
        if(ObjectUtils.isEmpty(users)){
            return TableDataInfo.build(result);
        }
        users.stream().forEach( user->{

            list.stream().forEach( applyCreatorsVo -> {
                if(applyCreatorsVo.getUserId().longValue() == user.getUserId().longValue()){
                    applyCreatorsVo.setUsername(user.getUsername());
                }
            });
        });

        return TableDataInfo.build(result);
    }

    /**
     * 查询作者申请审核功能列表
     */
    @Override
    public List<ApplyCreatorsVo> queryList(ApplyCreatorsBo bo) {
        LambdaQueryWrapper<ApplyCreators> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ApplyCreators> buildQueryWrapper(ApplyCreatorsBo bo) {
        LambdaQueryWrapper<ApplyCreators> lqw = Wrappers.lambdaQuery();
//       获取模糊查询的用户
        Set<Long> userIds = null;
        if(StringUtils.isNotBlank(bo.getUsername())){
            List<Users> username = usersMapper.selectList(new QueryWrapper<Users>().like("username", bo.getUsername()));
            if(ObjectUtil.isNotNull(username) && username.size() >0){
                userIds = username.stream().map(Users::getUserId).collect(Collectors.toSet());
            }else{
//                查询不到用户 给一个查不到的id
                userIds = new HashSet<>();
                userIds.add(-1l);
            }
        }
        lqw.in(userIds!= null, ApplyCreators::getUserId, userIds);
        lqw.eq(bo.getApplicationStatus() != null, ApplyCreators::getApplicationStatus, bo.getApplicationStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getApplicationInfo()), ApplyCreators::getApplicationInfo, bo.getApplicationInfo());

        lqw.eq(bo.getCreationTime() != null, ApplyCreators::getCreationTime, bo.getCreationTime());
        return lqw;
    }

    /**
     * 新增作者申请审核功能
     */
    @Override
    public Boolean insertByBo(ApplyCreatorsBo bo) {
        ApplyCreators add = MapstructUtils.convert(bo, ApplyCreators.class);
        validEntityBeforeSave(add);
//        添加默认值
        DFApplyCreators(add);
//        1.判断该用户是否已经是作者
        Long isCreaorts = creatorsMapper.selectCount(new LambdaQueryWrapper<Creators>().eq(Creators::getUserId, bo.getUserId()).eq(Creators::getStatus, CreatorsConstant.DFHY));
        if(isCreaorts>0){
            throw new ServiceException("该用户已经是作者无法创建！！");
        }
//        2.判断是否有申请 但未被打回的
        Long isApply = baseMapper.selectCount(new LambdaQueryWrapper<ApplyCreators>().eq(ApplyCreators::getUserId, bo.getUserId()).eq(ApplyCreators::getApplicationStatus, ApplyCreatorsConstant.DAI_APPLY));
        if(isApply>0){
            throw new ServiceException("该用户有申请记录未处理 无法再次创建！！！");
        }
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setUserCreatorsId(add.getUserCreatorsId());
        }
        return flag;
    }

    /**
     * 修改作者申请审核功能
     */
    @Override
    public Boolean updateByBo(ApplyCreatorsBo bo) {
        ApplyCreators update = MapstructUtils.convert(bo, ApplyCreators.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }
    /**
     * 添加默认值
     */
    public void DFApplyCreators(ApplyCreators add){
        add.setApplicationStatus(0l);
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ApplyCreators entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除作者申请审核功能
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public int changeStatus(ApplyCreatorsBo bo) {
        ApplyCreators update = MapstructUtils.convert(bo,ApplyCreators.class);
        //1.
        if(ObjectUtil.isNull(bo)){
            throw new ServiceException("信息不能为空 ！！");
        }
//        需要更新的用户
        Users users = new Users();
        users.setUserId(update.getUserId());
//        查询状态
        ApplyCreators applyCreators = baseMapper.selectById(bo.getUserCreatorsId());
//        从未审核到通过或退回
        if(ObjectUtil.isNotNull(applyCreators) && applyCreators.getApplicationStatus() == 0){
//            1.修改状态
            int i = baseMapper.updateById(update);
            if(i<=0){
                throw new ServiceException("更新失败 ！！");
            }
//            2.如果是通过 让用户创建一个作者
            if(bo.getApplicationStatus() == 1){
                int creatorsByUserId = usersService.createCreatorsByUserId(applyCreators.getUserId());
                if(creatorsByUserId <= 0){
                    throw new ServiceException("创建失败 ！！");
                }
                //            3. 并且更新用户角色
                users.setRole(UsersConstant.CREATORS_ROLE);
                usersMapper.updateById(users);
//                  3.通知表发送成功信息
                notificationsService.sendSystemMsg(update.getUserId(),"恭喜你 你已经成为创作者");
                return creatorsByUserId;
            }

            return 1;
        }
//        从通过到退回
        if(ObjectUtil.isNotNull(applyCreators) && applyCreators.getApplicationStatus() == 1 && bo.getApplicationStatus() == 2){
//            把当前状态修改为退回
            baseMapper.updateById(update);
//            把作者表状态修改为停用
            Creators creators = new Creators();
            creators.setStatus(CreatorsConstant.DFTY);
            int user_id = creatorsMapper.update( creators,new QueryWrapper<Creators>().eq("user_id", applyCreators.getUserId()));
//            把用户角色权限设置为用户
            users.setRole(UsersConstant.USERS_ROLE);
            usersMapper.updateById(users);
            //           todo 3.通知表发送退回信息
            notificationsService.sendSystemMsg(update.getUserId(),"你的创作者申请被驳回");
            return user_id;

        }

//        从退回到通过
        if(ObjectUtil.isNotNull(applyCreators) && applyCreators.getApplicationStatus() == 2 && bo.getApplicationStatus() == 1){
//              判断是否为最新申请
            List<ApplyCreators> applyCreators2 = baseMapper.selectList(new QueryWrapper<ApplyCreators>().eq("user_id", applyCreators.getUserId()).orderByDesc("creation_time"));
            if(applyCreators2 != null && applyCreators2.size() > 0){
                ApplyCreators applyCreators1 = applyCreators2.get(0);
                if (applyCreators1.getUserCreatorsId() != applyCreators.getUserCreatorsId()) {  // 不是最新申请 不能进行修改
                    throw new ServiceException("当前申请已经过期 请修改最新申请 ！！！");
                }
            }
//              判断是否存在作者
            Creators user_id = creatorsMapper.selectOne(new QueryWrapper<Creators>().eq("user_id", bo.getUserId()));
            if(ObjectUtil.isNotNull(user_id)){
//                修改状态 把停用变为活跃
                Creators c = new Creators();
                c.setStatus(CreatorsConstant.DFHY);
                c.setCreatorId(user_id.getCreatorId());
                int i = creatorsMapper.updateById(c);
                baseMapper.updateById(update);
//             把用户角色权限设置为作者
                users.setRole(UsersConstant.CREATORS_ROLE);
                usersMapper.updateById(users);
        //                 todo 3.通知表发送成功信息
                notificationsService.sendSystemMsg(update.getUserId(),"恭喜你 你已经成为创作者");
                return i;

            }
//              不存在创建一个
            int creatorsByUserId = usersService.createCreatorsByUserId(applyCreators.getUserId());
            if(creatorsByUserId <= 0){
                throw new ServiceException("创建失败 ！！");
            }
            //  把用户角色权限设置为作者
            users.setRole(UsersConstant.CREATORS_ROLE);
            usersMapper.updateById(users);
            //           todo 3.通知表发送成功信息
            notificationsService.sendSystemMsg(update.getUserId(),"恭喜你 你已经成为创作者");
            return creatorsByUserId;

        }
        throw new ServiceException("状态修改无效");
    }
}
